<?php
/**
 * Description of coreController
 * Main kse2 controller
 * standart kse2 engine class 
 * @author ixidor
 */

class coreController extends kseController{
    public $name = "coreController";
    
    //link to database
    private $link;
    
    public static $result;
    public static $matches;


    //general content types for page
    public $title;
    public $description;
    public $keywords;
    public $content;
    
    public $template_name = NULL;
    public $template_content;
    
    /* type of content to return: plane content, ALAX, etc
     * plane : 0; default
     * AJAX: 1;
     */
    
    public static $contentType = 0;
    
    /*
     * users types:
     * 0: users
     * 1: admins
     */
    public $user_type = 0;

    public function getNamespaces(){
        self::info("Collecting url namespaces");

        //admin login page url
        array_push($this->namespace, Core::get()->propertyList["ADMIN_LOGIN"]);
        array_push($this->namespace, Core::get()->propertyList["ADMIN_LOGOUT"]);
    }
    
    /*
    * route parsing method check wether file page exist and use proper model for
    * it
    */
    public function finder(){
        
        self::info("Trying to find a page");
        self::connectDB();
        
        //page exists and belongs to core controller
        if(!self::checkPage()){
            //throw 404 error
            self::printError(404);
        }
        
        //getting kse tags from template
        self::$matches = self::getTags();

        //create objects from tags
        self::makeObjects();
        
    }
    
    private function checkPage(){
        
        //$query = "SELECT page_title, page_keywords, page_description, page_content, page_template_id, page_locked FROM kse_site_pages WHERE page_filesystem_name='". self::$path ."'";
        //@todo trim linebreaks somehow
        $query = "SELECT SQL_NO_CACHE 
            t1.page_title,
            t1.page_description,
            t1.page_keywords,
            t1.page_content,
            t2.template_filesystem_name as template_name
        FROM kse_site_pages as t1,kse_site_templates as t2
        WHERE page_filesystem_name='". Core::get()->path ."' 
        AND t2.template_id = t1.page_template_id";
        
        $result = mysql_query($query);
        
        if(mysql_num_rows($result) > 0){
            self::$result = $result;
            list($this->title, $this->description, $this->keywords, $this->content, $this->template_name) = mysql_fetch_array($result);
            $this->info("Page found");
            $this->debug("Template name - ". $this->template_name);
            return TRUE;
        }
        else{
            //page not found
            //$this->debug("SQL statment is ". htmlentities($query));
            //using default template
            $this->template_name = "default.php";
            return FALSE;
        }
        
    }
    
    //show sys pages method
    public function showSysPage(){
        $this->template_name = "default.php";
        
        if(Core::get()->propertyList["PROTECTED_CONNECTION"]){
            $this->connectDB();
            
            $query = "SELECT * FROM kse_admin_ip_tables WHERE kse_admin_ip_name='". $_SERVER["REMOTE_ADDR"] . "'";
            $result = mysql_query($query) or Core::get()->kseDie(mysql_error());

            if(mysql_num_rows($result)){
                $protected = TRUE;
            }
        }
        else {
            $protected = TRUE;
        }

        if($protected){
            switch (Core::get()->path) {
                case "login/":
                    if($_POST){
                        $this->Login();
                    }

                    $this->title = "Login Page";
                    $this->content = $this->getContentFromURL("kse/core/pages/login.php");
                break;
                case "logout/":
                    session_destroy();
                break;
                default :
                    
                    $this->printError(404);
                break;
            }
        }
        else{
            $this->printError(404);
        }

        //getting kse tags from template
        self::$matches = self::getTags();

        //create objects from tags
        self::makeObjects();

    }

    public function makeResult($objects) {
        $this->checkSession();
        print_r($this->user_type);
        //if admin
        if($this->user_type > 0){
            $this->content .= $this->getAdminContent();
        }
        //including model
        self::kseInclude($_SERVER['DOCUMENT_ROOT'] ."/kse/core/coreModel.php", "Accesing core model");
        //initialize model
        $this->model = new coreModel();
        foreach ($objects as $object) {
            //get result from model
            $this->model->getResult($object);
        }

    }

    public function printResult(){

        //including view
        $this->kseInclude($_SERVER['DOCUMENT_ROOT'] ."/kse/core/coreView.php", "Accesing core view");
        //initialize view
        $this->view = new coreView();
        //displays result
        $this->view->displayResult();
        
        $this->disconnectDB();

    }

    public function printError($code){
        switch ($code) {
            case 404:
                $this->warn("Page ". Core::$path ." not found!");
                header("HTTP/1.0 404 Not Found");
                $this->title = "404 Page Not Found";
                $this->content = "404 Page Not Found";
            break;
        }

    }

    public function getTemplateFromURL($url){
        $this->debug(Core::get()->propertyList["PATH_TEMPLATES"] . $url);
        if(file_exists(Core::get()->propertyList["PATH_TEMPLATES"] . $url)){
            $url = Core::get()->propertyList["PATH_TEMPLATES"] . $url;
        }
        else {
            $this->warn("Template file doesn't exists");
            $url = Core::get()->propertyList["PATH_TEMPLATES"] . "default.php";
        }
        
        ob_start();
        ob_implicit_flush(0);
        self::kseRequire($url, "Including url - ". $url);
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }


    public function getTags(){
        
        self::info("Getting tags from template");
        
        $pattern = "/<kse owner=\"([A-z]+)\">([A-z]+)<\/kse>/";
        $this->template_content = self::getTemplateFromURL($this->template_name);
        
        /*
        * Result will be multi dimensional array with [0] => full tag match, [1] => owner, [2]=>object name
        */
        preg_match_all($pattern, $this->template_content, $matches, PREG_SET_ORDER);
        
        return $matches;
        
    }
    
    private function makeObjects(){
        
        $this->info("Creating Objects");
        foreach (self::$matches as $value) {
            Core::get()->nsObject[$value[1]."Controller"][$value[2]] = new Objects($value[2], $value[1], $value[0]);
        }
        
    }


    private function Login(){
        $query = "SELECT kse_admin_user_id, kse_admin_user_slvl FROM kse_admin_users WHERE kse_admin_user_password='". md5($_POST["pwd"]) . "' AND kse_admin_user_name='". $_POST["login"] ."'";
        $result = mysql_query($query) or Core::get()->kseDie(mysql_error());
        if(mysql_num_rows($result)){
                list($id, $slvl) = mysql_fetch_row($result);
                $_SESSION["user"] = $_POST["login"];
                $_SESSION["user_id"] = $id;
                $_SESSION["slvl"] = $slvl;

                $this->user_type = 1;

                self::info("Logged as Administrator");
                header("Location: ". Core::get()->propertyList["SITE_DOMAIN"]);
                
                //@todo check login

        }
        else{
            self::error("User or/and password mismatch");
        }
    }

    private function checkSession(){
       if(isset($_SESSION["slvl"]) && $_SESSION["slvl"]!=""){
           self::$user_type = 1;
           self::info("Administrator privilegias granted");
       }
    }
   
    private function getAdminContent(){
        //add admin js middleware
        self::info("Adding admin Content");
        return self::getContentFromURL("kse/core/pages/framework.php");
       
    }

    private function connectDB(){
        
        //Connecting to database
        $this->link = mysql_connect(Core::get()->propertyList["DB_HOST"], Core::get()->propertyList["DB_USER"], Core::get()->propertyList["DB_PASS"]) or die (self::error("Error establishing connetion to DATABASE"));
        
        //check if database exist
        if(!mysql_select_db(Core::get()->propertyList["DB_NAME"])){
            Core::get()->kseDie("Couldn't connect to DATABASE");
        }
        
        //Set correct encoding
        $query = "SET NAMES utf8";
        mysql_query($query) or Core::get()->kseDie(mysql_error() ."|". $query);
        
        self::info("Connectiong DATABASE........SUCCESED");
        
    }
    
    private function disconnectDB(){
        if($this->link){
            //disconnetction from db
            mysql_close($this->link);
            $this->info("Disconnecting from DB");
        }
        else{
            $this->warn("DB Link not found");
        }
        
        
    }
}
?>